package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Inventory;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.Unit;
import com.bree.erp.service.InventoryService;

@Stateless
public class InventoryServiceBean implements InventoryService {

	@PersistenceContext()
	private EntityManager em;
	
	public InventoryServiceBean() {
		
	}
	
	public InventoryServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public Inventory create(MasterItem entity) {
		Inventory inventory = new Inventory();
		
		inventory.setMasterItem(entity);
		
		Map<Unit, Double> units = createUnits(entity);
		inventory.setUnits(units);
		
		Map<Unit, Double> threasholds = createUnits(entity);
		inventory.setThreasholds(threasholds );
		
		em.persist(inventory);
		
		return inventory;
	}

	private Map<Unit, Double> createUnits(MasterItem entity) {
		
		Map<Unit, Double> units = new HashMap<Unit, Double>();
		
		
		return units;
	}

	@Override
	public Inventory read(Long id) {

		return em.find(Inventory.class, id);
	}

	@Override
	public void delete(Long id) {
		Inventory inventory = read(id);
		
		em.remove(inventory);
	}

	@Override
	public Inventory updateUnit(Long id, Unit unit, Double quantity) {
		Inventory inventory = read(id);
		
		inventory.getUnits().put(unit, quantity);
		
		return inventory;
	}

	@Override
	public Inventory updateThreashold(Long id, Unit unit, Double quantity) {
		
		Inventory inventory = read(id);
		
		inventory.getThreasholds().put(unit, quantity);
		
		return inventory;
	}

	@Override
	public Collection<Inventory> list() {
		TypedQuery<Inventory> query = em.createNamedQuery(Inventory.QUERY_SELECT_ALL_INVENTORY, Inventory.class);
		return query.getResultList();
	}

}
